package com.example.usbdemo

import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.IBinder
import android.util.Log
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import java.util.concurrent.Executors

class ConnectServiceKt : Service() {

    companion object {
        const val TAG = "USB 插拔信息"
        const val USB_SERIALPORT_ATTCHED = "HR_USB_SERIALPORT_ATTCHED"
        const val USB_SERIALPORT_DETACHED = "HR_USB_SERIALPORT_DETACHED"
        const val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"
    }

    private lateinit var mUsbPort: UsbSerialPort
    private lateinit var mUsbDriver: UsbSerialDriver
    private lateinit var mUsbDeviceConnection: UsbDeviceConnection
    private lateinit var mSerialIoManager: SerialInputOutputManager

    val mExecutor = Executors.newSingleThreadExecutor()

    override fun onCreate() {
        super.onCreate()
        val filter = IntentFilter()
        filter.addAction(USB_SERIALPORT_ATTCHED)
        filter.addAction(USB_SERIALPORT_DETACHED)
        registerReceiver(Br_UsbPermissionProc, filter)
//        registerReceiver(Br_UsbPermissionProc, filter)
    }

    private val Br_UsbPermissionProc = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            val action = p1?.action ?: return
            if (action == ACTION_USB_PERMISSION){
                val usbManager = baseContext.getSystemService(Context.USB_SERVICE) as UsbManager
                val pendingIntent =
                    PendingIntent.getBroadcast(baseContext, 0, Intent(ACTION_USB_PERMISSION), 0)
                usbManager.deviceList.values.forEach { item ->
                    if (usbManager.hasPermission(item)){
                        initSerialPort(usbManager, item)
                    }
                }
            }
        }

    }

    private fun initSerialPort(usbManager: UsbManager, usbDevice: UsbDevice) {
        Log.d(TAG, "CheckPermission:VID=" + usbDevice.vendorId + ",pid="+usbDevice.productId)
        UsbSerialProber.getDefaultProber().probeDevice(usbDevice)

    }

    override fun onBind(p0: Intent?): IBinder? {
        TODO("Not yet implemented")
    }
}